package com.jian.mygame;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

class MyAnimation extends Object {
	private Bitmap animation;
	private int xPos;
	private int yPos;
	private Rect sRectangle;
	private int fps;
	private int numFrames;
	private int currentFrame;
	private long frameTimer;
	private int spriteHeight;
	private int spriteWidth;
	private long gameTime;
	
	public static final int ANIMATION_TYPE_ONCE = 0;
	public static final int ANIMATION_TYPE_ALWAYS = 1;
	private int mDrawType; 
	
	private static final int STATE_STOP = 0;
	private static final int STATE_RUNNING = 1;
	private int mState;
	
	public MyAnimation() {
		sRectangle = new Rect(0, 0, 0, 0);
		frameTimer = 0;
		currentFrame = 0;
		xPos = 80;
		yPos = 200;
		mDrawType = ANIMATION_TYPE_ONCE;
		mState = STATE_STOP;
	}
	
	public void Initialize(Bitmap bitmap, int height, int width, int fps, int frameCount) {
		this.animation = bitmap;
		this.spriteHeight = height;
		this.spriteWidth = width;
		this.sRectangle.top = 0;
		this.sRectangle.bottom = spriteHeight;
		this.sRectangle.left = 0;
		this.sRectangle.right = spriteWidth;
		this.fps = 1000 / fps;
		this.numFrames = frameCount;
	}
	
	public void setAnmiationType( int type ){
		mDrawType = type;
	}
	
	public void setPosition(int x, int y) {
		xPos = x;
		yPos = y;
	}
	
	public void updateTimer() {
		gameTime = System.currentTimeMillis();
		
		if( gameTime > frameTimer + fps) {
			frameTimer = gameTime;
			
			if( STATE_RUNNING == mState) {
				sRectangle.left = currentFrame * spriteWidth;
				sRectangle.right = sRectangle.left + spriteWidth;
				
				if( ++currentFrame >= numFrames ) {
					currentFrame = 0;
					if( ANIMATION_TYPE_ONCE == mDrawType ){
						mState = STATE_STOP;
					}
				}
			}
		}
	}
	
	public void start(){
		mState = STATE_RUNNING;
	}
	
	public boolean onDraw(Canvas canvas) {
		boolean bRet = true;
		
		if( STATE_RUNNING == mState) {
			Rect dest = new Rect(xPos-spriteWidth/2, yPos-spriteHeight/2, xPos + spriteWidth/2, yPos + spriteHeight/2);
			
			canvas.save();
			
			//canvas.drawColor(Color.BLACK); //Clear the screen before the next tile is drawn
			canvas.drawBitmap(animation, sRectangle, dest, null);
			
			canvas.restore();
			
			bRet = true;
		} else {
			bRet = false;
		}
		
		return bRet;
	}
}
